package com.ahccc.codegenerator;

import com.ahccc.framework.common.text.SymbolConst;
import com.ahccc.framework.mybatis.base.common.response.BaseResponse;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

@Controller
@RequestMapping("/file")
public class FileController {

    @ResponseBody
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public Object download(@RequestParam(name="path", required=true) String path,
                           HttpServletRequest request, HttpServletResponse response) throws Exception {

        String fileName = path;
        String[] strings = StringUtils.split(path, SymbolConst.SLASH);
        if(strings.length > 0){
            fileName = strings[strings.length-1];
        }
        response.setContentType("text/plain");
        response.setHeader("Content-disposition","attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path);
        if( !file.exists()){
            throw new Exception("文件不存在");
        }
        OutputStream out = response.getOutputStream();
        FileInputStream in = new FileInputStream(file);
        byte[] buffer = new byte[4096];
        int length;
        while ((length = in.read(buffer)) > 0){
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();
        return BaseResponse.success().build();
    }
}
